package com.xsmart.fileserver.services;

import com.xsmart.common.entity.fileupload.FileUpload;
import com.xsmart.common.entity.user.AdminUser;
import com.xsmart.fileserver.dao.FileUploadDao;
import com.xsmart.fileserver.entity.FileMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;

@Service
public class FileUploadService {
    @Autowired
    private UserService userService;
    @Autowired
    private FileUploadDao fileUploadDao;

    @Value("${fileUpload.path}")
    private String path;
    public static Random r = new Random();

    public LinkedList<FileMeta> adminuUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
        String token = request.getParameter("token");
        AdminUser adminUser = userService.checkToken(token);
        return upload(request, response, "shop", adminUser.getUserId());
    }

    public LinkedList<FileMeta> userUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
        String token = request.getParameter("token");
        AdminUser adminUser = userService.checkToken(token);
        return upload(request, response, "user", adminUser.getUserId());
    }

    private LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response, String uploadType, long userId) {
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
        FileMeta fileMeta = null;
        //1. build an iterator
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf = null;

        //2. get each file
        while (itr.hasNext()) {

            //2.1 get next MultipartFile
            mpf = request.getFile(itr.next());
            System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());

            //2.2 if files > 10 remove the first from the list
            if (files.size() >= 1)
                files.pop();

            //2.3 create new fileMeta
            fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            fileMeta.setFileType(mpf.getContentType());
            int idx = mpf.getOriginalFilename().lastIndexOf(".");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = df.format(System.currentTimeMillis()) + Math.abs(r.nextInt()) + mpf.getOriginalFilename().substring(idx);
            fileMeta.setFileUrl(fileName);
            try {
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path + fileName));
                FileUpload fileUpload = new FileUpload();
                fileUpload.setImageUrl(path + fileName);
                fileUpload.setUploadTime(new Date());
                fileUpload.setUploadUserId(userId);
                fileUploadDao.saveFileUpload(fileUpload);
                fileMeta.setFileId(fileUpload.getImageId());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //2.4 add to files
            files.add(fileMeta);
        }
        return files;
    }


}
